/*
 * @Description:获取验证码的按钮组建
 * @Author: tao.xie
 * @Date: 2019-03-21 16:29:39
 * @Last Modified by: tao.xie
 * @Last Modified time: 2019-03-29 10:45:52
 */
<template>
  <span
    @click.stop="click"
    class=" get-code-btn"
    :class="isRunning?'baseColorInvalid':'baseColorWithActive'"
  >{{isRunning?tipsTemplate:buttonText}}</span>
</template>

<script>
// 倒计时时间，默认为60秒
const RESET_SECONDS = 60
// 当倒计时开始倒计时时触发的事件
const START_RUNNING_EVENT_NAME = 'vclick'
export default {
  watch: {
    second(val) {
      if (val === 0) {
        this.reset()
      }
    }
  },
  computed: {
    // 验证码倒计时的提示文案，如果需要修改继承后重写
    tipsTemplate() {
      return this.second + 's'
    }
  },
  data() {
    return {
      second: RESET_SECONDS,
      timer: null,
      isRunning: false,
      buttonText: '获取验证码'
    }
  },
  methods: {
    click: function () {
      if (!this.isRunning) { this.$emit(START_RUNNING_EVENT_NAME) }
    },
    run: function () {
      if (!this.isRunning) {
        this.isRunning = true
        if (this.timer != null) {
          window.clearInterval(this.timer)
        }
        this.timer = setInterval(() => {
          this.second--
        }, 1000)
      }
    },
    reset: function () {
      if (this.timer != null) {
        window.clearInterval(this.timer)
      }
      this.isRunning = false
      this.second = RESET_SECONDS
    }
  }
}
</script>

<style scoped>
.get-code-btn {
  font-size: 14px; /*no*/
  line-height: 20px; /*no*/
}
</style>
